﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;
using System.Configuration;
using AteneoLibri.Utility.Mail;

namespace AteneoLibri.BackEnd
{
    public partial class Newsletter : System.Web.UI.Page
    {
        List<User> users = new List<User>();
        protected void Page_Load(object sender, EventArgs e)
        {
            // Retrieve users
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                try
                {
                    users = service.getUsers();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }                
            }
        }

        protected void btnSendEmail_Click(object sender, EventArgs e)
        {
            string text = CKEditor1.Text; // HttpUtility.HtmlEncode()
            text += MailText.NewsletterComunicationsFooter();

            // Send email to the comunications mail box to take trace of the history of the messages
            Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
            string account = ConfigurationManager.AppSettings["MAIL_ComunicationSender"].ToString();
            mailSender.SendMail(account, "Comunicazione da AteneoLibri.it", text, true);

            int marketingType = Convert.ToInt16(ddlMarketingNewsletter.SelectedValue);

            List<User> marketingUsers = this.users;

            switch (marketingType)
            {
                case 2:
                    marketingUsers = marketingUsers.Where(x => x.MarketingNewsletter == null || (x.MarketingNewsletter.HasValue && x.MarketingNewsletter.Value)).ToList();                    
                    break;
                default:
                    break;
            }

            SendMarketingMail(marketingUsers, text);                    

            pnlWYSIWYG.Visible = false;
            pnlConfirmSendEmail.Visible = true;
        }

        private void SendMarketingMail(List<AteneoLibriBusinessLogic.Entities.User> marketingUsers, string text)
        {
            Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
            List<string> emails = marketingUsers.Select(x => x.Email).ToList();
            mailSender.SendBulkMail(emails, "Comunicazione da AteneoLibri.it", text, true);

            // GESTIRE LA TEMPORIZZAZIONE AL CRESCERE DEGLI UTENTI
            //foreach (var item in marketingUsers)
            //{
            //    mailSender.SendComunicationMail(item.Email, "Comunicazione da AteneoLibri.it", text, true);
            //}
        }
    }
}